package com.zdp.dubbo.simulate.framework.protocol.http;

import com.zdp.dubbo.simulate.framework.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * 消费者通过 HttpClient 发送消息
 * @author ZhengDp
 * @Date 2023/6/4 12:18
 */
public class HttpClient {

    public String send(String hostName, Integer port, Invocation invocation) {
        // 读取用户的配置 ==> 用户可以自己选择要使用哪个工具包去发送消息
        try {
            URL url = new URL("http",hostName,port,"/");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            OutputStream outputStream = connection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);

            oos.writeObject(invocation);
            oos.flush();
            oos.close();

            InputStream inputStream = connection.getInputStream();
            String result = IOUtils.toString(inputStream);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
